<?php

/* @project : Template
 * @auther  : 青云
 * @date    : 2018/1/10
 * @desc    : 登录控制器
 */

namespace app\admin\controller;

use app\api\controller\Util;
use app\common\model\RoleAdmin;
use Naixiaoxin\ThinkWechat\Facade;
use think\Controller;
use think\facade\Config;
use think\facade\Session;
use think\Request;
use app\common\model\Admin as AdminModel;

class Login extends Controller
{

    public function index()
    {
        return $this->fetch();
    }

    function check_login(Request $request)
    {
        if (!empty($request->account)) {
            $account = $request->account;
        } else {
            $this->error('登录名不能为空');
        }

        if (!empty($request->password)) {
            $password = $request->password;
        } else {
            $this->error('密码不能为空');
        }

        // $result_verify = (new Util())->check_verify($request->captcha, 'array');

        // if (0 == $result_verify['code']) {
        //     $this->error('验证码输入错误');
        // }

        $AdminModel = new AdminModel();
        $admin_info = $AdminModel->login($account, $password);
        if ($admin_info !== null) {
            // 记录登录状态 保存session
            Session::set(Config::get('config.admin_auth_key'), $admin_info['id']);
            Session::set('account', $admin_info['account']);
            Session::set('user_name', $admin_info['name']);
            $roleInfo = (new RoleAdmin())->singleData(['admin_id'=>$admin_info['id']], 'role_id');
            Session::set('role_id', $roleInfo['role_id']);
            if (empty($admin_info['avatar'])) {
                Session::set('avatar', Config::get('avatar_path') . '/default.jpg');
            }
            $this->success('登录成功');

        } else {
            $this->error('用户名或密码错误');
        }
    }

    public function logout()
    {
        $auth_id = Session::get(Config::get('config.user_auth_key'));
        if (isset($auth_id)) {
            Session::clear();
            $this->redirect('login/index');
        } else {
            $this->redirect('login/index');
        }
    }
}
